package com.zlyx.easy.netty.client.defaults;

import java.util.ArrayList;
import java.util.List;

import com.zlyx.easy.core.hex.Hex;
import com.zlyx.easy.core.utils.ThreadUtils;
import com.zlyx.easy.netty.client.core.AbstractNettyClient;

import io.netty.channel.ChannelHandler.Sharable;

/**
 * @Auth 赵光
 * @Desc Netty阻塞式->长连接->客户端
 * @Date 2019年4月28日
 */
@Sharable
public abstract class DefaultNettyClient extends AbstractNettyClient<Hex>{
	
	private List<String> list = new ArrayList<>();
	
	private boolean isInterrupt;
	
	private int waittime;
	
	private String data;
	
	public DefaultNettyClient(String key, String host, int port) throws Exception {
		this(key, host, port, 3000);
	}
	
	public DefaultNettyClient(String key, String host, int port, int waittime) throws Exception {
		super(key, host, port);
		this.waittime = waittime;
		this.isInterrupt = false;
	}

	/**
	 * 发送数据
	 * @param data
	 * @return
	 * @throws Exception 
	 */
	public void doSend(String data) throws Exception {
		this.list.add(data);
	}
	
	@Override
	public void run() {
		try {
			super.run();
			while(!isInterrupt) {
				if(this.list.size() > 0){
					this.data = this.list.remove(0);
					this.write(Hex.newHex(data));
				}
				ThreadUtils.sleep(waittime);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
	
	public void close(){
		super.close();
		this.isInterrupt = true;
	}
}
